<?php

namespace app\models;

use yii\db\ActiveRecord;

/**
 * 用户套餐流量池
 * Class UserPackagePool
 * @package app\models
 *
 * @property integer $id PK
 * @property integer $uid 用户编号
 * @property integer $package_id 套餐编号
 * @property string $month 月份
 * @property float $data_pool 流量池
 * @property float $data_used 使用量
 *
 * @property Package $package 关联套餐
 */
class UserPackagePool extends ActiveRecord
{
    /**
     * 关联套餐
     * @return \yii\db\ActiveQuery
     */
    public function getPackage()
    {
        return $this->hasOne(Package::class, ['id' => 'package_id']);
    }

    /**
     * 返回当前流量池卡数量
     * @return int
     */
    public function getCardCount()
    {
        $activeEndTime = strtotime($this->month . '01');
        return Card::find()
            ->andWhere(['uid' => $this->uid])
            ->andWhere(['package_id' => $this->package_id])
            ->andWhere(['<', 'active_time', $activeEndTime])
            ->andWhere(['status' => Card::STATUS_ACTIVATED])
            ->count();
    }

    /**
     * 计算并更新流量池
     * @param integer $uid 用户编号
     * @param integer $packageId 套餐编号
     * @param string $month 月份
     */
    public static function calcPool($uid, $packageId, $month = null)
    {
        if (empty($month)) {
            $month = date('Ym');
        }
        $pool = UserPackagePool::findOne(['uid' => $uid, 'package_id' => $packageId, 'month' => $month]);
        if (empty($pool)) {
            $pool = new UserPackagePool();
            $pool->uid = $uid;
            $pool->package_id = $packageId;
            $pool->month = $month;
        }
        $pool->data_pool = $pool->package->data * $pool->getCardCount();
        $activeEndTime = strtotime($month . '01');
        $dataUsed = Card::find()
            ->andWhere(['uid' => $uid])
            ->andWhere(['<', 'active_time', $activeEndTime])
            ->andWhere(['package_id' => $packageId])
            ->sum('data');
        $pool->data_used = floatval($dataUsed);
        $pool->save();
    }
}
